<template>
		<view class="course">
			<view class="head">
				<view class="uni-padding-wrap uni-common-mt">
				            <view class="video-container">
								<!-- https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4 -->
						<!-- https://media.w3.org/2010/05/sintel/trailer.mp4 -->
						<!-- http://vjs.zencdn.net/v/oceans.mp4 -->
								<!-- https://cdn.uviewui.com/uview/resources/video.mp4 -->
								<!-- http://www.w3school.com.cn/example/html5/mov_bbb.mp4 -->
								
								<!-- https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209105011F0zPoYzHry.mp4 -->
								<!-- https://www.w3schools.com/html/movie.mp4 -->
								<!-- https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4 -->
								<!-- https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209104902N3v5Vpxuvb.mp4 -->
				                <video id="myVideo" :src="path" @play="onPlay"  
				                    @error="videoErrorCallback" :danmu-list="danmuList" enable-danmu danmu-btn controls></video>
				            </view>
							
							<view>
										<!-- 普通弹窗 -->
								<uni-popup ref="popup" background-color="#fff" @change="change">
									<view class="popup-content" >
										<text class="text"  v-if="isActive">课程打{{active.discount}}折支付{{course.price*active.discount}}￥即可观看所有视频</text>
										<text class="text" v-else>支付{{course.price}}￥即可观看所有视频</text>
										
									</view>
									<view class="popup-content">
										<button type="primary" size="mini" @click="buy">立即购买</button>
									</view>
								</uni-popup>
								
							</view>
							
							
							

				            <!-- #ifndef MP-ALIPAY -->
				           <!-- <view class="uni-list uni-common-mt">
				                <view class="uni-list-cell">
	
				                    <view class="uni-list-cell-db">
				                        <uni-easyinput v-model="danmuValue" class="uni-input" type="text" placeholder="在此处输入弹幕内容" />
				                    </view>
				                </view>
				            </view>
				            <view class="uni-btn-v">
				                <button @click="sendDanmu" class="page-body-button">发送弹幕</button>
				            </view> -->
				            <!-- #endif -->
				</view>
				<view class="context">
					
								<view class="uni-padding-wrap uni-common-mt">
									<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem"  />
								</view>
								<view class="content">
									<view v-if="current === 0">
										 <view class="car">
											<uni-group mode="card"> 
												<uni-title type="h3" :title="course.title" ></uni-title>
												<rich-text :nodes="description.description"></rich-text>
											</uni-group>
											<view class="top"></view>
										 </view>	
													 
									</view>
									
									<view v-if="current === 1" class="list1">
									 <view>	
										<uni-list>
													<uni-list>
													  <uni-list-item :title="'共'+course.lessonNum+'课时'" />
																	
													</uni-list>
													<uni-list-item v-for="(item,index) in videos" :key="index">
														<template v-slot:body>
															<view class="slot-box">
																
																 <text class="slot-text" :class="{selected:index===selectedItemId }" @click="getPath(item.videoSourceId,index)">{{(index+1)+":"+item.title}}</text>
																
															</view>
														</template>
													</uni-list-item>
										</uni-list>	
									 </view>		

									
									</view>
									
									<view v-if="current === 2">
										<view class="comments">
											<comment ref='comm'  :course="course" ></comment>
											<!-- <text class="content-text">没有更多评论</text> -->
										</view>
										
									</view>
								</view>
					
					
								
						
				</view>	
			</view>
			
		   <courseFootBar v-if="current!=2" :course="course" :discount="isActive?active.discount:1" @buyPopu="handleNotify"></courseFootBar>  
		  <commentFootBar  @newComment="handleNewComment" v-else  :course="course"></commentFootBar>
		</view>
		
		
		<view class="order">
				<uni-popup ref="byCourse" background-color="#fff"  type='bottom'>
						<view class="popup-content">
							
					
							<uni-section title="提交订单">
										<uni-list>
											
											<uni-list-item :title="course.title" :note="course.price+'￥'" 
												:thumb="course.cover" thumb-size="lg"
												 rightText="长期有效" />
											
											<uni-list-item v-if="isActive" title="优惠活动" :rightText="'打'+active.discount+'折'" />	 
											<uni-list-item v-else title="无优惠活动" rightText="无" />
											<uni-list-item  title="金额" :rightText="isActive?active.discount*course.price+'￥':course.price+'￥'" />
											
											<view >	 
											<hr>
												 <view class="radio-group-container">
													<text>支付方式</text> 
												 	<radio-group @change="radioChange" >
												 		<label class="radio-label">
												 			<radio value="0" checked="flgRadio" />
												 			<image class="uni-share-image" src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/c2b17470-50be-11eb-b680-7980c8a877b8.png" mode="aspectFill"></image>
												 			<span>微信支付&nbsp;&nbsp;</span>
															<radio value="1" />
															<image class="uni-share-image" src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/d684ae40-50be-11eb-8ff1-d5dcf8779628.png" mode="aspectFill"></image>
															<span>支付宝支付</span>
												 		</label>
												 		
												 	</radio-group>
												 </view>
											</view>
											
											<uni-list-item title="购买即视为同意概不退款" class="center-title" />
											<button type="primary" style="width: 98%;" @click="pay"> 购买</button>

										</uni-list>
									
							</uni-section>
						</view>
					</uni-popup>
		</view>
		
		
		<view class="qrPop">
			<uni-popup ref="qrPop" background-color="#fff" @change="change">
							<view class="popup-content" >
								<vueQr
								           :text='qr'
								           :margin="0"
								           colorDark="black"
								           colorLight="white"
								           
								         
								     ></vueQr>
							</view>
			</uni-popup>
		</view>	   
		
	 
	  
		
	
</template>

<script setup>
	import {apiGetCourse,apiGetVideos,apiGetDescription,apiGetActive,apiCreateOrder,apiCreateAliQr,apiQueryZFBPayStatus,updateCourseBuyCount} from '@/apis/course.js'
	import {apiGetTeacherById} from '@/apis/teacher.js'
	import vueQr from '../../node_modules/vue-qr/src/packages/vue-qr.vue'
     
	let couresId=uni.getStorageSync("BuyCourses")		
	
	let items=ref(['简介','目录','评论'])
	const current=ref(0)
	

	
	const onClickItem=(e)=> {
			if (current !== e.currentIndex) {
						current.value=e.currentIndex
			} 
	}
	
	
	
			

	const course=ref({})
	const tearcherId=ref(0)

	const getCourse = async (id)=>{
		let res = await apiGetCourse(id)
		course.value = res.data.data
		tearcherId.value=course.value.teacherId
		getTeacher()
		console.log("获取课程信息");
		console.log(course)
	}
	
	
	
	
	const teacher=ref({})
	
	
	const getTeacher=async ()=>{

		console.log("====================================");
		console.log(tearcherId.value);
		let res=await apiGetTeacherById(tearcherId.value)
		teacher.value=res.data.data
		console.log("获取教师信息");
		console.log(teacher.value);
		
	}
	
	
	const videos=ref([])
	const path=ref("https://www.w3schools.com/html/movie.mp4");
	const getVideos = async (id)=>{
		let res = await apiGetVideos(id)
		videos.value = res.data.data
		path.value=res.data.data[0].videoSourceId
		console.log("获取视频信息");
		console.log(videos.value)
	}	
		
		
	const description=ref({})
	
	
	
	const getDescription = async (id)=>{
		let res = await apiGetDescription(id)
		description.value = res.data.data
		console.log("获取课程描述信息");
		console.log(description)
	}		
			
			
			
			
	
	onLoad((e)=>{
		let id=e.id
		
		getVideos(id)
		getCourse(id)
		getDescription(id)
		getActive(id)
	
		
	
		
		
			
	})	
	
	
	const src = ref('');
	const danmuList = ref([
	  {
	    text: '第 1s 出现的弹幕',
	    color: '#ff0000',
	    time: 1
	  },
	  {
	    text: '第 3s 出现的弹幕',
	    color: '#ff00ff',
	    time: 3
	  }
	]);
	const danmuValue = ref('');
	
	
	let videoContext = null;
	
	onReady(() => {
	  videoContext = uni.createVideoContext('myVideo');
	});
	 
	
	// 发送弹幕的方法
	const sendDanmu=()=> {
	  if (videoContext) {
	    videoContext.sendDanmu({
	      text: danmuValue.value,
	      color: getRandomColor()
	    });
	    danmuValue.value = '';
	  }
	}
	
	// 视频错误回调函数
	const videoErrorCallback=(e)=> {
		console.log("==========视频错误=============");
		console.log(e);
	 uni.showModal({
	    content: e.target.errMsg,
	    showCancel: false
	  });
	}
	
	// 随机生成颜色的方法
	const getRandomColor=()=> {
	  const rgb = [];
	  for (let i = 0; i < 3; ++i) {
	    let color = Math.floor(Math.random() * 256).toString(16);
	    color = color.length == 1 ? '0' + color : color;
	    rgb.push(color);
	  }
	  return '#' + rgb.join('');
	}
	
	const selectedItemId=ref(0) 
	

	const getPath=(src,index)=>{
		console.log("===========点击时间触发了============");
		if(couresId.includes(course.value.id)||course.value.price===0){
			console.log("========index======");
			selectedItemId.value=index;
			path.value=src
			console.log("获取视频路径");
			console.log(path.value)
		}else{
			uni.showToast({
				//title:res.data.msg,
				title:'请先购买课程',
				//icon:"none"
				icon:"none"
			})
		}
		
	}
	
	let type= ref('buttom')
	
	const popup = ref(null)
	
	const onPlay=()=>{
		console.log("==========播放按钮触发了=========");
		
		console.log("==========================");
		if(!couresId.includes(course.value.id)&&course.value.price!=0){
		
				console.log("=========未购买==========");
				videoContext.pause()
				popup.value?.open()
				if(!isCreateOrder.value){
					console.log("==========正在生成订单=============");
					createOrder()
					
				} 
			
		}
	}
	
	const change=(e)=> {
					console.log('当前模式：' + e.type + ',状态：' + e.show);
    }
	
	const active=ref({
		discount:1 
	})
	const isActive=ref(false)
	const getActive=async (courseId)=>{
		let res=await apiGetActive(courseId)
		if(res.data.code===200){
			active.value=res.data.data
			isActive.value=true
			console.log("购买课程优惠活动");
			console.log(active.value);
		}
	}
	
	
	
	const handleNotify=()=>{
		byCourse.value?.open()
	}
	
	
	const flgRadio=ref(true)
	
	const payFor=ref(0)
	
	const radioChange=(e)=>{
		console.log("==============radioChange============");
		console.log(e.detail.value);
		payFor.value=e.detail.value
		flgRadio.value=!flgRadio.value
	}
	
	const member=uni.getStorageSync("member")
	

	
	const byCourse=ref(null)
	const buy=()=>{
		console.log("==========购买按钮执行了=========");
		byCourse.value?.open()
		popup.value?.close()
		
		
	}
	
	const qrPop=ref(null)
	const order=ref({})
	const createOrder=async ()=>{
		
		
		let orderVo={
			courseId:course.value.id,
			courseTitle:course.value.title,
			totalFee:isActive.value?course.value.price*active.value.discount:course.value.price,
			payType:payFor.value,
			teacherName:teacher.value.name,
			courseCover:course.value.cover,
			memberId:member.id,
			nickname:member.nickname,
			mobile:member.mobile
			
		}
	
	   
		let res=await apiCreateOrder(orderVo)
		if(res.data.code==200){
			order.value=res.data.data
			isCreateOrder.value=true
			console.log("==========生成订单==========order.vaule============");
			console.log(order.value);
			if(payFor.value==0){
				createWeiXinQr()
		
			}
			if(payFor.value==1){
				createAliQr()
				
			}
			
		}
	}
	const interval=ref(null)
	const qr=ref("")
	const createWeiXinQr=async ()=>{
		let res=await apiCreateWeiXinQr(order.value)
		if(res.data.code==200){
			qr.value=res.data.data
			console.log("==========微信二维码地址==========");
			console.log(qr.value);
			qrPop.value?.open()
			
		}
	}
	
	
	
	const createAliQr=async()=>{
		let res=await apiCreateAliQr(order.value)
		if(res.data.code==200){
			qr.value=res.data.data
			console.log("==========支付宝二维码地址==========");
			console.log(qr.value);
			qrPop.value?.open()	
			interval.value=setInterval(()=>{
			    console.log("定时器执行了");
			    queryZFBPayStatus();
			  },5000)
		}
	}
	
	const isCreateOrder=ref(false)
	const pay=()=>{
		console.log("购买按钮触发了");
		if(!isCreateOrder.value){
			createOrder()
		}else{
			if(payFor.value==0){
				createWeiXinQr()
			}
			if(payFor.value==1){
				createAliQr()
			}
			
		}		
	}
	
	
	//查询支付宝支付状态
	const queryZFBPayStatus=async()=>{
	  console.log("查询支付状态");
	  let res=await apiQueryZFBPayStatus(order.value.orderNo);
	  if(res.data.code==400){
	    return;
	  }
	  console.log("支付结果");
	  console.log(res);
	  clearInterval(interval.value);
	  
	  qr.value="";
	  uni.showToast({
	  	title: '支付成功',
	  	duration: 2000
	  });
	  
	  //修改课程
	  
	  interval.value=null
	  qrPop.value?.close() 
	  let byCourse=uni.getStorageSync("BuyCourses")	
	  byCourse.push(course.value.id);
	  uni.setStorageSync("BuyCourses",byCourse)
	  uni.navigateTo({
	  	url:"/pages/course/course?id="+course.value.id
	  })
	}
	
	
	
	const updateBuyCount=async()=>{
		let res=await apiUpdateBuyCount(course.value.id)
		if(res.data.code==200){
			console.log("更新销售数量成功");
		}
	}
 
	const comm=ref(null)
    const handleNewComment = (newComment) => {
		
		console.log("=============触发评论刷新了==================");
		console.log(comm.value);
		console.log(newComment);
		if(comm.value){
			comm.value?.getComments()
		}
	}

	
	
	
	
	
	

	
	
	
	
	
	
	

	
	
	
	
	
	
	
	
	
	
	
</script>

<style lang="scss" scoped>
.course{
	width: 100%;	
	.head{
		width: 100%;
		height: 400rpx;
		uni-video {
			width: 100%;
			height: 225px;
			display: inline-block;
			line-height: 0;
			overflow: hidden;
			position: relative;
		}
		
		.popup-content {
				@include flex;
				align-items: center;
				justify-content: center;
				padding: 15px;
				height: 50px;
				background-color: #fff;
		}

		.context{
				width: 100%;
				padding: 0rpx;
				margin: 0rpx;
				.list1{
					width: 100%;
					.slot-text {
					  color: black;
					  cursor: pointer;
					}
					.selected {
					  color: blue; /* 选中时的颜色 */
					}
				}
				.comments{
					width: 100%;
				}
				
				
				.uni-common-mt {
					margin-top: 0rpx;
				}
			
				.uni-padding-wrap {
					width: 400rpx;
					padding: 0,30rpx;
				}
				.car{
					.top{
						height: 100rpx;
						
					}
				}	
				.content {
					/* #ifndef APP-NVUE */
					display: flex;
					/* #endif */
					justify-content: left;
					align-items: left;
					height: 150px;
					text-align: center;
				}
			
				.content-text {
					font-size: 14px;
					color: #666;
				}
			
				.color-tag {
					width: 25px;
					height: 25px;
				}
			
				.uni-list {
					flex: 1;
				}
			
				.uni-list-item {
					/* #ifndef APP-NVUE */
					display: flex;
					/* #endif */
					flex: 1;
					flex-direction: row;
					background-color: #FFFFFF;
				}
			
			
				.uni-list-item__container {
					padding: 12px 15px;
					width: 100%;
					flex: 1;
					position: relative;
					/* #ifndef APP-NVUE */
					display: flex;
					box-sizing: border-box;
					/* #endif */
					flex-direction: row;
					justify-content: space-between;
					align-items: center;
					border-bottom-style: solid;
					border-bottom-width: 1px;
					border-bottom-color: #eee;
				}
			
				.uni-list-item__content-title {
					font-size: 14px;
				}
				
				
				
		}	
		
		

	}

}
.order{
		
		.radio-group-container {
			width: 100%;
			height: 80rpx;
			display: flex; /* 启用 Flexbox 布局 */
			flex-direction: row; /* 设置主轴方向为水平 */
			align-items: center; /* 垂直居中对齐 */
			
			.radio-label {
				display: flex; /* 启用 Flexbox 布局 */
				align-items: center; /* 垂直居中对齐 */
				margin-left: 100rpx; /* 为每个选项添加间距 */
				.uni-share-image {
					width: 50rpx; /* 设置图片宽度 */
					height: 50rpx; /* 设置图片高度 */
					margin-right: 20rpx; /* 图片与文字之间的间距 */
				}
			}	
		
			
		}
		
		.center-title {
		    text-align: center;
		}
		
		
		
	}



	  
	  
	  
	  


</style>
